﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using XuanXiang.Infrastructure.Attr;
using XuanXiang.Infrastructure.Dto.Request;
using XuanXiang.Infrastructure.Dto.Request.Goods;
using XuanXiang.Infrastructure.Dto.Request.Login;
using XuanXiang.Infrastructure.Dto.Request.Merchant;
using XuanXiang.Infrastructure.Dto.Response;
using XuanXiang.Infrastructure.Dto.Response.Merchant;
using XuanXiang.Infrastructure.EFCore.MySql;
using XuanXiang.Infrastructure.Tools;
using XuanXiang.Service.Instance;
using XuanXiang.Service.Interface;

namespace XuanXiang.Api.Admin.Controllers.Wechat
{
    
    [ApiGroup("Wechat(微信模块)")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WechatMerchantController : ControllerBase
    {
        private readonly I_Merchant_Service _merchant_Service;
        private readonly IConfiguration _configuration;
        private readonly I_Pomote_Service _pomote_Service;

        public WechatMerchantController(IConfiguration configuration,
          
            I_Merchant_Service merchant_Service,
            I_Pomote_Service pomote_Service)
        { 
            _merchant_Service = merchant_Service;
            _configuration = configuration;
            _pomote_Service = pomote_Service;
        }


        /// <summary>
        /// 商户登录
        /// {account/password}
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]

        public async Task<IActionResult> Merchant_Logins(Login_dto dto)
        {

            dto.code = Config.GUID2();
            var data = await _merchant_Service.Merchant_Logins(dto);
            if (data.code == Api_Code.ok)
            {
                var claims = new[]
                    {
                    new Claim(ClaimTypes.Name,  dto.code),
                     new Claim(ClaimTypes.Actor,  dto.account!),
                    new Claim(ClaimTypes.Role,"merchant")//角色设定
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                    issuer: jwtKey,
                    audience: jwtKey,
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(60 * 12), //token 过期时间
                    signingCredentials: creds);

                data.data = new
                {

                    token = new JwtSecurityTokenHandler().WriteToken(token)
                };

            }

            return Ok(data);
        }

        /// <summary>
        /// 获取当前登录的商户
        /// </summary>
        /// <returns></returns>
        private Merchant_Dto Get_Merchant()
        {
            var code = Response.HttpContext.User.Identity?.Name;

            return _merchant_Service.Check_Merchant_Login(code!,"");
        }

        /// <summary>
        /// 检查商户登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Check_Merchant_Login()
        {
            await Task.Delay(1);
            var merchant = this.Get_Merchant();
            if (merchant == null)
            {
                return Unauthorized();//401
            }
            return Ok(new Api_Result_Dto()
            {
                code = 0,
                message = "ok",
                data = merchant
            });
        }



        /// <summary>
        /// 商户-获取活动商品
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Get_Merchant_PromoteGoods(int page = 1, int limit = 10) 
        {
            var merchant = this.Get_Merchant();
            if (merchant == null)
            {
                return Unauthorized();//401
            }
            var result = await _pomote_Service.Get_Merchant_PromoteGoods(new Fenye_Dto() { 
            page = page,
            limit = limit,
            id=merchant.id
            });
            return Ok(result);


        }

        /// <summary>
        /// 商户-获取热门商品
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Merchant_GetHotGoods() {
            var result = await _merchant_Service.Merchant_GetHotGoods();
            return Ok(result);
        }

        /// <summary>
        /// 商户-获取热卖榜单商品
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Merchant_GetHotBuyGoods(int page=1,int limit=10) {
            var result = await _merchant_Service.Merchant_GetHotBuyGoods(new Fenye_Dto() { 
            page=page,
            limit = limit,
            });
            return Ok(result);
        }


        /// <summary>
        /// 商户-获取单个商品详情{id}
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Merchant_GetSingleGoods(string? id) {
            var result = await _merchant_Service.Merchant_GetSingleGoods(id);
            return Ok(result);
        }

        /// <summary>
        /// 商户-新增商品到购物车
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Add_MerchantCar(Add_Car_Dto dto) 
        {
            await Task.Delay(1);
            var merchant = this.Get_Merchant();
            if (merchant == null) {
                return Unauthorized();
            }
            dto.mid = merchant.id;
            Api_Result_Dto result =await _merchant_Service.Add_MerchantCar(dto);
            return Ok(result);

        }

        /// <summary>
        /// 商户-获取我的购物车
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Merchant_GetMyCar() {

            var merchant = this.Get_Merchant();
            if (merchant == null) {
                return Unauthorized();//401
            }

            var result =await _merchant_Service.Merchant_GetMyCar(merchant.id);
            return Ok(result);
        }

        /// <summary>
        /// 商户-购物车更新
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Update_Cars(Cars_Dto dto) 
        {
            var merchant = this.Get_Merchant();
            if (merchant == null)
            {
                return Unauthorized();//401
            }

            var result = await _merchant_Service.Update_Cars(merchant.id,dto.cars);
            return Ok(result);
        }

        /// <summary>
        /// 商户-从购物车移除商品
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Merchant_RemoveCar(Add_Car_Dto dto) {
           
            var merchant=this.Get_Merchant();
            if (merchant == null)
            {
                return Unauthorized();//401
            }

            dto.mid=merchant.id;
            
            var result = await _merchant_Service.Merchant_RemoveCar(dto);
            return Ok(result);
        }


        /// <summary>
        /// 商户-提交订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Merchant_CreateOrder(Add_Orders_Dto dto) 
        {
            var merchant=this.Get_Merchant(); 
            if (merchant == null)
            {
                return Unauthorized();
            }
            var result = await _merchant_Service.Merchant_CreateOrder(merchant.id, dto);
            return Ok(result);
        }

       /// <summary>
       /// 商户-商品搜索
       /// </summary>
       /// <param name="page"></param>
       /// <param name="limit"></param>
       /// <param name="key"></param>
       /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Merchant_SearchGoods(int page=1,int limit=100, string? key="") {
            var result = await _merchant_Service.Merchant_SearchGoods(
                new Fenye_Dto() { 
            page=page, limit=limit, key=key??""
            });
            return Ok(result);
        }


        /// <summary>
        /// 商户-获取商品详情中的猜你喜欢商品
        /// {id:商品类型id}
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Merchant_GetLikeGoods(string? gid,string? tid) {
            var result = await _merchant_Service.Merchant_GetLikeGoods(gid,tid);
            return Ok(result);
        }

        /// <summary>
        /// 商户-获取订单
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="type">1 2 3 4</param>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Merchant_Get_Orders(int page = 1, int limit = 10, int type = 1) {
            var merchant = this.Get_Merchant();
            if (merchant == null)
            {
                return Unauthorized();//401
            }
            var result = await _merchant_Service.Merchant_Get_Orders(new Fenye_Dto()
            {
                page = page,
                limit = limit,
                type = type,
                id = merchant.id
            });

            return Ok(result);
        }

        /// <summary>
        /// 商户订单-取消订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Merchant_CancelOrder(IsBan_Dto dto)
        {
           
            var result = await _merchant_Service.Merchant_CancelOrder(dto);
            return Ok(result);
        }

        /// <summary>
        /// 商户-获取订单统计数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "merchant")]
        public async Task<IActionResult> Merchant_GetMeStatistics() {
            var merchant = this.Get_Merchant();
            if (merchant == null)
            {
                return Unauthorized();//401
            }

            var result = await _merchant_Service.Merchant_GetMeStatistics(merchant.id);
            return Ok(result);
        }

        
        /// <summary>
        /// 商户-获取单个订单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Merchant_GetSingleOrder(string? id) {
            var result =await _merchant_Service.Merchant_GetSingleOrder(id);
            return Ok(result);
        }

        /// <summary>
        /// 商户-收货
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Merchant_ReceiveGoods(Merchant_Dto dto) 
        {
            var result =await _merchant_Service.Merchant_ReceiveGoods(dto.id);
            return Ok(result);
        }


        /// <summary>
        /// 商户-获取我的订单详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Merchant_GetAllOrder(int page = 1, int limit = 10, int type = 1)
        {
            var merchant = this.Get_Merchant();
            if (merchant == null)
            {
                return Unauthorized();//401
            }

       
            var result =await _merchant_Service.Merchant_GetAllOrder(new Fenye_Dto()
            {
                page = page,
                limit = limit,
                type = type,
                id = merchant.id
            });
            return Ok(result);
        }

        /// <summary>
        /// 商户-获取我的页面的未发货订单
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Merchant_Me_GetNoSendOrder(int page = 1, int limit = 10, int type = 1) {
            var merchant = this.Get_Merchant();
            if (merchant == null)
            {
                return Unauthorized();//401
            }


            var result = await _merchant_Service.Merchant_Me_GetNoSendOrder(new Fenye_Dto()
            {
                page = page,
                limit = limit,
                type = type,
                id = merchant.id
            });
            return Ok(result);
        }

        /// <summary>
        /// 商户-获取我的页面的已取消订单
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Merchant_Me_GetCancelOrder(int page = 1, int limit = 10, int type = 1)
        {
            var merchant = this.Get_Merchant();
            if (merchant == null)
            {
                return Unauthorized();//401
            }


            var result = await _merchant_Service.Merchant_Me_GetCancelOrder(new Fenye_Dto()
            {
                page = page,
                limit = limit,
                type = type,
                id = merchant.id
            });
            return Ok(result);
        }
    }
}

